# -*- coding: utf-8 -*-
import requests,time,datetime
from lxml import etree
import redis
import time,random
import atx,pymysql
from multiprocessing import Pool
import logging
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib



logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(process)d - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)





class Lianlianpay():
    def __init__(self):
        self.session = requests.session()


    def recharge(self,phone,money,cookie):
        recharge = 'http://www.aikaixin.com/topup/recharge.do'
        data = {
            'hidispid':None,
            'hidareacode':None,
            'custTime':time.strftime("%Y%m%d-%H%M%S", time.localtime()),
            'ctimestamp':time.time(),
            'custcode':phone,
            'faceMoney':money,
            'paypassword':'060716',
            'goodsValue':'0%7C%7C68%7C102337%7C102337%7CSCDXM001%7C1%7C10%7C2000%7C.9972%7C29%7C04',
            'payMethods':'0',
            'ntpwd':'0'
        }
        r = self.session.post(recharge, data = data, headers = {'Cookie':cookie})
        if u'\u5f00\u5fc3\u8fde\u8fde' not in r.text:
            logger.error('Cookie已失效，请重新登录')
            exit()

    def query(self,phone,cookie):
        query_url = 'http://www.aikaixin.com/topupOrder/orderList.do'
        data = {
            'nowPage': '1',
            'begin': '1',
            'num': '10',
            'status': None,
            'ispid': None,
            'loginname': None,
            'begindate': time.strftime("%Y-%m-%d", time.localtime()),
            'enddate': time.strftime("%Y-%m-%d", time.localtime()),
            'custcode': phone,
        }

        r = requests.post(query_url,data = data,headers = {'Cookie':cookie})
        html = etree.HTML(r.text)
        create_time = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[1]')
        order_id = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[2]')
        number = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[3]')
        result = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[7]/span')
        money = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[5]')
        result_list = []
        for a,b,c,d,e in zip(order_id,number,result,money,create_time):
            query_list = {
                'order_id':''.join(a.text.split()),
                'number':b.text,
                'result':c.text,
                'money':d.text,
                'create_time':str(e.text).encode('utf-8'),
            }
            result_list.append(query_list)
        return result_list



def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))



def send_email(addr,title,text):
    from_addr = 'ysmlfx@163.com'
    password = 'qweasdzxc123'
    to_addr = addr
    smtp_server = 'smtp.163.com'
    msg = MIMEText(text, 'plain', 'utf-8')
    msg['From'] = _format_addr('姚航 <%s>' % from_addr)
    msg['To'] = _format_addr('陈吉全 <%s>' % to_addr)
    msg['Subject'] = Header(title, 'utf-8').encode()
    server = smtplib.SMTP(smtp_server,25,timeout=10)
    server.set_debuglevel(0)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()



def listen_task(cookie):

    rcon = redis.StrictRedis(host=u'localhost')
    queue = u'yaohang'
    logger.info('程序已启动，正在等待新任务....')

    while True:

        task = rcon.blpop(queue)
        info = eval(task[1])
        logger.info(u"获取到新订单---%s" % info)

        phone_number = info['phone_number']
        money = info['money']
        ID = info['ID']
        logger.info(u'开始充值' )
        lianlian = Lianlianpay()
        lianlian.recharge(phone_number,money,cookie)
        logger.info(u'订单已提交')
        time.sleep(15)
        logger.info('开始查询结果')
        result = lianlian.query(phone_number,cookie)
        if len(result) != 1:
            logger.info('有多条查询结果，请人工核实')
            sql = '''INSERT INTO Recharge_record(order_id,phone_number,money,result,mobile_order_id,paid,account,date) VALUES (%s,%s,%s,'%s',%s,%s,'%s',now())''' % (ID, phone_number, int(result[0]['money']), 'verify', result[0]['order_id'], int(result[0]['money']),'lianlian')
            try:
                db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
                cursor = db.cursor()
                cursor.execute(sql)
                db.commit()

            except:
                db.rollback()
                logger.warning(u"订单数据写入失败---%s,%s" % (phone_number))
            db.close()
        else:
            if result[0]['result'] == u'\u6210\u529f':  # 成功
                fff = 'success'
                logger.info('%s 充值成功'%phone_number)
            elif result[0]['result'] == u'\u5931\u8d25':  # 失败
                fff = 'failure'
                logger.info('%s 充值失败' % phone_number)
            elif result[0]['result'] == u'\u5f85\u786e\u8ba4':  # 待确认
                fff = 'verify'
                logger.info('%s 充值结果待确认' % phone_number)
            sql = '''INSERT INTO Recharge_record(order_id,phone_number,money,result,mobile_order_id,paid,account,date) VALUES (%s,%s,%s,'%s',%d,%s,'%s',now())''' % (ID, phone_number, result[0]['money'], fff, result[0]['order_id'], result[0]['money'],'lianlian')
            try:
                db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
                cursor = db.cursor()
                cursor.execute(sql)
                db.commit()

            except:
                db.rollback()
                logger.warning(u"订单数据写入失败---%s,%s" % (phone_number))
            db.close()


if __name__ == '__main__':
    listen_task('payMethods=0; JSESSIONID=771C5A41EC1E2E0EAF76697FC0925051; redisid=677811D140224B015EAD7B2B503AAFC6')

